import type { DeptAndUser, TreeNodeData } from '@/api/common';
import type { TData } from './props';
import { cloneDeep } from 'lodash';

/**树节点转换 */
export const fmtToTData = (
  data: TreeNodeData,
  disabledMethod?: (data: TreeNodeData) => boolean,
  filterMethod?: (data: TreeNodeData) => boolean
): TData | undefined => {
  if (filterMethod?.(data)) return undefined;
  return {
    id: data.id,
    name: data.name,
    key: `dept:${data.id}`,
    type: 1,
    children: data.children
      ?.map((item) => fmtToTData(item, disabledMethod))
      .filter((x) => x !== undefined) as TData[],
    disabled: disabledMethod ? disabledMethod(data) : false
  };
};
// 拍平TreeData 数据
export const flatTreeData = (data: TData[], result: TData[] = []) => {
  for (let i = 0; i < data.length; i += 1) {
    const item = data[i];
    result.push(item);
    if (item.children) {
      flatTreeData(item.children, result);
    }
  }
  return result;
};

// 格式化人员信息对部门信息进行合并
export const genUserDeptsData = (data: TData[]) => {
  const flatDataClone = cloneDeep(flatTreeData(data));
  return flatDataClone.reduce<TData[]>((pre, cur) => {
    if (cur.type == 2) {
      const targetUser = pre.findIndex((el: any) => el.id == cur.id);
      if (targetUser < 0) {
        return pre.concat(cur);
      } else {
        pre[targetUser].deptInfo = pre[targetUser].deptInfo.concat(
          cur.deptInfo
        );
        return pre;
      }
    } else {
      return pre;
    }
  }, []);
};

// 部门和人员转换函数
export const transFormDpetUser = (
  data: DeptAndUser,
  parentDept?: DeptAndUser,
  disabledMethod?: (data: unknown) => boolean,
  filterMethod?: (data: unknown) => boolean
): TData | undefined => {
  if (filterMethod?.(data)) return undefined;
  let userAndDept: TData[] = [];
  if (data.personals) {
    data.personals.forEach((person) => {
      if (!filterMethod?.(person)) {
        userAndDept.push({
          id: person.uid,
          name: person.name,
          key: `dept:${data.id}/user:${person.uid}`,
          type: 2,
          roles: person.roles,
          deptInfo: [
            parentDept
              ? [
                  { id: parentDept.id, name: parentDept.name },
                  { id: data.id, name: data.name }
                ]
              : [{ id: data.id, name: data.name }]
          ],
          disabled: disabledMethod ? disabledMethod(person) : false
        });
      }
    });
  }
  if (data.children) {
    const children: TData[] = [];
    for (let i = 0; i < data.children.length; i++) {
      if (!filterMethod?.(data.children[i])) {
        const child = transFormDpetUser(
          data.children[i],
          data,
          disabledMethod,
          filterMethod
        );
        if (child !== undefined) {
          children.push(child);
        }
      }
    }
    userAndDept = userAndDept.concat(children);
  }
  return {
    id: data.id,
    name: data.name,
    key: `dept:${data.id}`,
    type: 1,
    children: userAndDept
  };
};
